<?php
namespace base\tools;

use think\facade\Log;

define('ENABLE_HTTP_PROXY', FALSE);
define('HTTP_PROXY_IP', '127.0.0.1');
define('HTTP_PROXY_PORT', '8888');

class HttpHelper
{
	public static $connectTimeout = 30;//30 second
	public static $readTimeout = 80;//80 second
	public static $isThrow = true;//是否抛出异常
	
	public static function curl($url, $httpMethod = "GET", $postFields = null,$headers = null)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); 
		if(ENABLE_HTTP_PROXY) {
			curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); 
			curl_setopt($ch, CURLOPT_PROXY, HTTP_PROXY_IP); 
			curl_setopt($ch, CURLOPT_PROXYPORT, HTTP_PROXY_PORT);
			curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); 
		}
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FAILONERROR, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postFields) ? self::getPostHttpBody($postFields) : $postFields);
		
		if (static::$readTimeout) {
			curl_setopt($ch, CURLOPT_TIMEOUT, static::$readTimeout);
		}
		if (static::$connectTimeout) {
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, static::$connectTimeout);
		}
		//https request
		if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		}
		if (is_array($headers) && 0 < count($headers))
		{
			$httpHeaders =self::getHttpHearders($headers);
			curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeaders);
		}
		
		$data = curl_exec($ch);

		// Log::error('返回信息:'.$data);

		$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		if (curl_errno($ch))
		{	
			$info = "Server unreachable: Errno: " . curl_errno($ch) . " " . curl_error($ch);
			if(static::$isThrow){
				return_error(["info"=>$info]);
			}

			Log::error('请求地址：'.$url.' 错误信息:'.$info);
			return false;	
		}
		
		curl_close($ch);

		return $data;
    }
    
	static function getPostHttpBody($postFildes){		
		$content = "";
		foreach ($postFildes as $apiParamKey => $apiParamValue)
		{			
			$content .= "$apiParamKey=" . urlencode($apiParamValue) . "&";
		}
		return substr($content, 0, -1);
    }
    
	static function getHttpHearders($headers)
	{
		$httpHeader = array();
		foreach ($headers as $key => $value)
		{
			array_push($httpHeader, $key.":".$value);	
		}
		return $httpHeader;
	}
}